#!/usr/bin/python3
#接收信息并更新CMDB中记录

import json, sys, requests, time, socket
from aliyun import *
from bkcmdb import *

#位置
CONF_SITE="/root/bin/cmdb/script_conf.cfg"

#当前master监听
host = "10.0.12.9"
port = 9527

def update_server(host_ip, dict_info):
    aliyun_inst = AliYun(CONF_SITE)
    bkcmdb_inst = BkCmdb(CONF_SITE)

    #先添加VPC信息
    aliyun_inst.vpc_info_dict = aliyun_inst.get_vpc()

    #获取id号
    inq_dict = {"bk_host_innerip": host_ip}
    if bkcmdb_inst.get_host_id(inq_dict) == 0:
        bkcmdb_inst.create_host(host_ip)
    host_id = bkcmdb_inst.get_host_id(inq_dict)

    #合并字典
    ecs_info_dict = aliyun_inst.get_ecs_info(host_ip)
    ecs_info_dict = dict( ecs_info_dict, **dict_info )

    #更新 
    bkcmdb_inst.update_host(host_id, ecs_info_dict)

#持续监听端口，对客户端传入的数据进行监控项和触发器添加
def main():
    serversocket=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
    serversocket.bind((host,port))
    serversocket.listen(500) #最大连接数
    while True:
        print('服务器启动，监听客户端链接')
        clientsocket,addr=serversocket.accept()
        data=clientsocket.recv(1024000)
        dict_info = eval(data.decode('utf-8')) #变成字典
        host_ip = dict_info['host_ip']
        print(host_ip + "开始更新")
        del dict_info['host_ip']
        update_server(host_ip, dict_info)
        print("")
        clientsocket.close()
    serversocket.closel()

if __name__ == '__main__':
    main()
